<template>
    <!-- 单场考试分析 -->
    <div class="one-exam-analysis">
        <el-row type="flex" justify="space-between">
            <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
                <el-form-item>
                    <!-- 选择考试场次 -->
                    <el-select filterable @change="search" v-model="searchForm.examId" placeholder="请选择考试场次">
                        <el-option
                            v-for="item in examOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <div v-if="examOptions.length > 0">
            <el-row>
                <el-col :span="24">
                    <h3 class="text-center">试卷：{{ exampaperInfo.name }}</h3>
                </el-col>
            </el-row>
            <!-- 试卷基础情况 -->
            <p class="model-title">试卷基础情况</p>
            <el-row class="overview-wrap" type="flex" justify="space-between">
                <el-col :span="4">
                    <div class="item-wrap">
                        <p class="item-value color-3">100分</p>
                        <p class="item-title">试卷总分</p>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="item-wrap">
                        <p class="item-value color-2">{{ exampaperInfo.passLine }}分</p>
                        <p class="item-title">及格线</p>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="item-wrap">
                        <p class="item-value color-5">{{ exampaperInfo.totalQuestionNum }}题</p>
                        <p class="item-title">考题总数</p>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="item-wrap">
                        <p class="item-value color-4">{{ exampaperInfo.examCount }}人</p>
                        <p class="item-title">应考人数</p>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="item-wrap">
                        <p class="item-value color-6">{{ exampaperInfo.examFinishCount }}人</p>
                        <p class="item-title">实际参考人数</p>
                    </div>
                </el-col>
            </el-row>
            <!-- 考试统计 -->
            <el-row :gutter="20">
                <el-col :span="24">
                    <p class="model-title">考试统计</p>
                </el-col>
                <!-- 及格率 -->
                <el-col :span="12">
                    <div id="passRateEchart" class="echart-wrap"></div>
                </el-col>
                <!-- 正确率 -->
                <el-col :span="12">
                    <div id="correctRateEchart" class="echart-wrap"></div>
                </el-col>
            </el-row>
            <el-row v-show="hasDepartmentData">
                <el-col :span="24">
                    <el-form class="department-serach-form" ref="searchForm2" :model="searchForm2" :inline="true" @submit.native.prevent>
                        <el-form-item>
                            <!-- 选择部门 -->
                            <tree-select
                                placeholder="请选择部门"
                                v-model="searchForm2.departmentId"
                                filterable
                                :width="200"
                                :data="orgOptions"
                                :defaultProps="typeDefaultProps"
                                :checkedKeys="defaultCheckedDepartmentId"
                                :nodeKey="typeNodeKey">
                            </tree-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button class="form-search-btn" type="primary" @click="searchDepartment">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <!-- 部门考试情况 -->
            <el-row class="overview-wrap" type="flex" justify="space-between" v-show="hasDepartmentData">
                <el-col :span="6">
                    <div class="item-wrap">
                        <p class="item-value color-4">{{ departmentExamInfo.avgScore }}分</p>
                        <p class="item-title">平均得分</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="item-wrap">
                        <p class="item-value color-2">{{ departmentExamInfo.minScore }}分</p>
                        <p class="item-title">最低得分</p>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="item-wrap">
                        <p class="item-value color-3">{{ departmentExamInfo.maxScore }}分</p>
                        <p class="item-title">最高得分</p>
                    </div>
                </el-col>
            </el-row>
            <el-row v-show="hasDepartmentData">    
                <el-col :span="24">
                    <div class="examinee-score-distributed-wrap">
                        <p class="echart-title text-center">考生得分分布</p>
                        <P class="text-center">
                            <el-radio-group v-model="searchForm2.type" @change="getExamineeScoreByOrg">
                                <el-radio-button label=1>10分一个区间</el-radio-button>
                                <el-radio-button label=2>5分一个区间</el-radio-button>
                            </el-radio-group>
                        </P>
                        <div id="examineeScoreDistributedEchart" class="echart-wrap"></div>
                    </div>
                </el-col>
            </el-row>
            <el-row v-show="hasDepartmentData">    
                <el-col :span="24">
                    <div class="examinee-score-distributed-wrap">
                        <p class="echart-title text-center">考生得分排名</p>
                        <P class="text-center">
                            <el-radio-group v-model="searchForm2.sortType">
                                <el-radio-button label='asc'>正排</el-radio-button>
                                <el-radio-button label='desc'>倒排</el-radio-button>
                            </el-radio-group>
                        </P>
                        <div id="examineeScoreSortEchart" class="echart-wrap"></div>
                    </div>
                </el-col>
            </el-row>
            <!-- 暂无数据 -->
            <div v-if="!hasDepartmentData" class="no-data">
                <p class="no-data-text">暂无部门数据</p>
            </div>
            <!-- 考试明细 -->
            <el-row>
                <el-col :span="20">
                    <p class="model-title">考试明细</p>
                </el-col>
                <el-col :span="4">
                    <el-row type="flex" justify="end">
                        <el-button type="primary" @click="exportDetail">导出明细</el-button>
                    </el-row>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-row type="flex" class="type-item-wrap">
                        <el-col :span="24" class="exam-detail-table">
                            <el-table
                                v-loading="loading"
                                border
                                ref="examDetailTable"
                                :data="tableData"
                                style="width: 100%">
                                <el-table-column label="序号" type="index" width="50"></el-table-column>
                                <el-table-column label="组织" prop="organization"></el-table-column>
                                <el-table-column label="部门" prop="department"></el-table-column>
                                <el-table-column label="职位" prop="postName"></el-table-column>
                                <el-table-column label="考生" prop="examAccountName"></el-table-column>
                                <el-table-column label="答题开始时间" prop="beginTime"></el-table-column>
                                <el-table-column label="耗时" prop="costTime"></el-table-column>
                                <el-table-column label="得分" prop="score"></el-table-column>
                                <el-table-column label="排名" prop="ranking">
                                    <template slot-scope="scope">
                                        <p v-if="scope.row.status == 0">缺考</p>
                                        <p v-else-if="scope.row.status == 1">考试进行中</p>
                                        <p v-else>{{ scope.row.ranking }}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column label="答卷明细" width="100">
                                    <template slot-scope="scope">
                                        <el-button v-if="scope.row.status == 2" @click="handleDetail(scope.row)" type="text" size="small">查看</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination
                                background
                                small
                                @current-change="handleCurrentChange"
                                @size-change="handleSizeChange"
                                :current-page.sync="currentPage"
                                :page-sizes="[10, 50, 100]"
                                :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total">
                            </el-pagination>
                        </el-col>
                    </el-row>
            
                </el-col>
            </el-row>
        </div>
        <!-- 暂无数据 -->
        <div v-if="examOptions.length == 0" class="no-data">
            <p class="no-data-text">暂无考试信息</p>
        </div>
        <!-- 考生答卷明细 -->
        <el-dialog
            :close-on-click-modal="false"
            title="答卷"
            width="1200px"
            top='10vh'
            v-if="dialogExamPaper"
            :visible.sync="dialogExamPaper"
            @close="closeExamPaper"
            v-dialogDrag>
            <examinee-answer-sheet-view :oldInfo="currentExamPaperInfo" :closeFun="closeExamPaper"></examinee-answer-sheet-view>
        </el-dialog>
    </div>
</template>
<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import { getDepartmentTree } from '@/api/department'
import { getExamInfoListByOrgIds, getExamInfo, getExamPassCount, getQuestionTypeCount, getScoreCount, getExamDetailForCalc, getExamDetailInfo } from '@/api/exam'
import ExamineeAnswerSheetView from '@/components/Examination/Common/ExamineeAnswerSheetView'

export default {
    name: 'OneExam',
    components: {
        TreeSelect,
        ExamineeAnswerSheetView
    },
    data() {
        return {
            examOptions: [], // 考试场次下拉框数据
            searchForm: {
                examId: ''
            },
            exampaperInfo: {},
            hasDepartmentData: false,
            orgOptions: [], // 部门下拉框数据
            typeDefaultProps: {
                children: 'nodes',
                label: 'name',
                value: 'id'
            },
            typeNodeKey: 'id',
            defaultCheckedDepartmentId: [],
            searchForm2: {
                departmentId: '',
                type: 1, // 1:10分区间,2:5分区间
                sortType: 'asc' // 升序 asc 降序 desc
            },
            departmentExamInfo: {},
            loading: true,
            tableData: [],
            // 分页
            currentPage: 1,
            pageSize: 10,
            total: 0,
            currentExamPaperInfo: {},
            dialogExamPaper: false
        }
    },
    created() {
        this.getExamOptionsData()
    },
    methods: {
        mapQuestionType(key) {
            let MapList = {
                1: '判断题',
                2: '单选题',
                3: '多选题'
            }

            return MapList[key]
        },
        // 获取考试场次信息
        getExamOptionsData() {
            getExamInfoListByOrgIds({
                orgIds: this.$store.state.userinfo.org.id + ',' + this.$store.state.userinfo.organizationIds
            }).then(res => {
                if(res.status === 200) {
                    this.examOptions = res.data
                    if(res.data.length > 0) {
                        // 默认选择第一个
                        this.searchForm.examId = res.data[0].id
                        this.search()
                        this.getOrgData()
                    }
                }
            })
        },
        search() {
            this.getExamPaperInfo()
            this.getPassRateData()
            this.getCorrectRateData()
            this.getTableData(1, 10)
        },
        // 获取试卷基础情况
        getExamPaperInfo() {
            getExamInfo({
                id: this.searchForm.examId
            }).then(res => {
                if(res.status === 200) {
                    this.exampaperInfo = res.data
                }
            })
        },
        // 获取及格率
        getPassRateData() {
            getExamPassCount({
                infoId: this.searchForm.examId
            }).then(res => {
                if(res.status === 200) {
                    this.renderPassRateEchart(res.data)
                }
            })
        },
        // 渲染及格率饼图
        renderPassRateEchart(data) {
            // 基于准备好的dom，初始化echarts实例
            let $dom = document.getElementById('passRateEchart')
            if($dom) {
                this.$echarts.init($dom).setOption({
                    color: ['#47CFAD', '#FD5E5E'],
                    title: {
                        textStyle: { color: '#2F3444', fontSize: '16' },
                        y: 'left',
                        left: '15',
                        top: '0',
                        text: '及格率统计',
                    },
                    grid: {
                        left: '3%',
                        right: '3%',
                        top: '35px',
                        bottom: '30px'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b}: {c} ({d}%)"
                    },
                    series: [
                        {
                            name:'及格率',
                            type:'pie',
                            radius: ['0%', '82%'],
                            avoidLabelOverlap: false,
                            label: {
                                formatter: "{b}: {c}({d}%)",
                                emphasis: {
                                    show: true,
                                    textStyle: {
                                        fontSize: '20',
                                        fontWeight: 'bold'
                                    }
                                }
                            },
                            labelLine: {
                                normal: {
                                    show: true
                                }
                            },
                            data:[
                                {value:data.passNum, name:'及格人数'},
                                {value:data.nopassNum, name:'不及格人数'}
                            ]
                        }
                    ]
                })
            }
        },
        // 获取题型正确率
        getCorrectRateData() {
            getQuestionTypeCount({
                infoId: this.searchForm.examId
            }).then(res => {
                if(res.status === 200) {
                    this.renderCorrectRateEchart(res.data)
                }
            })
        },
        // 渲染题型正确率柱状图
        renderCorrectRateEchart(data) {
            let that = this
            let xData = []
            let yData = []
            $.each(data, (i, obj)=>{
                xData.push(this.mapQuestionType(obj.questoinType))
                yData.push({
                    value: obj.percent,
                    // itemStyle:{ normal: { color: that.colorList[i] } }
                })
            })
            let option_echart = {
                color: ['#70bbea', '#5c90d2', '#a58ad4'],
                title: {
                    textStyle: { color: '#2F3444', fontSize: '16' },
                    y: 'left',
                    left: '15',
                    top: '0',
                    text: '题型正确率',
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: function (e) {
                        var data = e[0]
                        return data.seriesName + '<br/>' + data.marker + data.name + '：' + data.value + '%'
                    }
                },
                xAxis: {
                    type: 'category',
                    axisTick: {
                        show: false
                    },
                    triggerEvent: true,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            width: 1, //这里是为了突出显示加上的
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        },
                        interval:0
                    },
                    boundaryGap: true,
                    data: xData
                },
                yAxis: {
                    type: 'value',
                    axisTick: {
                        show: false
                    },
                    min: 0,
                    max: 100,
                    axisLine: {
                        show: false,
                    },
                    axisLabel: {
                        formatter: '{value}%',
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            opacity: 0.7
                        }
                    },
                    axisPointer: {
                        snap: true
                    },
                    minInterval: 1
                },
                series: [{
                    name: "正确率",
                    type: 'bar',
                    barWidth: '30',
                    itemStyle: {
                        normal: {
                            color: '#5c90d2',
                        }
                    },
                    label: {
                        formatter: '{c}%',
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    },
                    data: yData
                }]
            }
            that.$echarts.init(document.getElementById('correctRateEchart')).setOption(option_echart, true);
        },
        // 获取部门下拉框数据
        getOrgData() {
            getDepartmentTree({
                orgId: this.$store.state.userinfo.org.id,
                orgIds: this.$store.state.userinfo.organizationIds
            }).then(res => {
                if(res.status === 200) {
                    this.orgOptions = res.data
                    if(res.data.length > 0) {
                        // 默认选择第一个
                        this.searchForm2.departmentId = res.data[0].id
                        this.$nextTick(() => {
                            this.defaultCheckedDepartmentId = res.data[0].id.toString().split(',')
                        })
                        this.hasDepartmentData = true
                    } else {
                        // 没有部门数据
                        this.hasDepartmentData = false
                    }
                }
            })
        },
        // 查询部门统计情况
        searchDepartment() {
            this.getExamineeScoreByOrg()
            this.getExamineeScoreSort()
        },
        // 获取部门考生得分统计
        getExamineeScoreByOrg() {
            getScoreCount({
                examId: this.searchForm.examId,
                type: this.searchForm2.type,
                departmentId: this.searchForm2.departmentId
            }).then(res => {
                if(res.status === 200) {
                    this.departmentExamInfo = res.data
                    this.renderExamineeScoreDistributedEchart(res.data)
                    this.hasDepartmentData = true
                } else {
                    this.hasDepartmentData = false
                }
            })
        },
        // 渲染考生得分分布柱状图
        renderExamineeScoreDistributedEchart(data) {
            let that = this
            let xData = []
            let yData = []
            $.each(data.trend, (i, obj)=>{
                xData.push(obj.key)
                yData.push({
                    value: obj.value,
                    // itemStyle:{ normal: { color: that.colorList[i] } }
                })
            })
            let option_echart = {
                color: ['#70bbea', '#5c90d2', '#a58ad4'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: function (e) {
                        var data = e[0]
                        return data.seriesName + '<br/>' + data.marker + data.name + '：' + data.value + '人'
                    }
                },
                xAxis: {
                    type: 'category',
                    axisTick: {
                        show: false
                    },
                    triggerEvent: true,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            width: 1, //这里是为了突出显示加上的
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        },
                        interval:0
                    },
                    boundaryGap: true,
                    data: xData
                },
                yAxis: {
                    type: 'value',
                    name: '人数',
                    axisTick: {
                        show: false,
                    },
                    min: 0,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}',
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            opacity: 0.7
                        }
                    },
                    axisPointer: {
                        snap: true
                    },
                    minInterval: 1
                },
                series: [{
                    name: "得分",
                    type: 'bar',
                    barWidth: '30',
                    itemStyle: {
                        normal: {
                            color: '#5c90d2',
                        }
                    },
                    label: {
                        formatter: '{c}%',
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    },
                    data: yData
                }]
            }
            that.$echarts.init(document.getElementById('examineeScoreDistributedEchart')).setOption(option_echart, true);
        },
        // 获取考生得分排名统计
        getExamineeScoreSort() {
            getExamDetailForCalc({
                examInfoId: this.searchForm.examId,
                departId: this.searchForm2.departmentId,
                sort: this.searchForm2.sortType
            }).then(res => {
                if(res.status === 200) {
                    this.renderExamineeScoreSortEchart(res.data)
                }
            })
        },
        // 渲染考生得分排名柱状图
        renderExamineeScoreSortEchart(data) {
            let that = this
            let xData = []
            let yData = []
            $.each(data, (i, obj)=>{
                xData.push(obj.examAccountName)
                yData.push({
                    value: obj.score
                })
            })
            let option_echart = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: function (e) {
                        var data = e[0]
                        return data.seriesName + '<br/>' + data.marker + data.name + '：' + data.value + '分'
                    }
                },
                xAxis: {
                    type: 'category',
                    axisTick: {
                        show: false
                    },
                    triggerEvent: true,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            width: 1, //这里是为了突出显示加上的
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        },
                        interval:0
                    },
                    boundaryGap: true,
                    data: xData
                },
                yAxis: {
                    type: 'value',
                    name: '分数',
                    axisTick: {
                        show: false
                    },
                    min: 0,
                    max: 100,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}',
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        }
                    },
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            opacity: 0.7
                        }
                    },
                    axisPointer: {
                        snap: true
                    },
                    minInterval: 1
                },
                series: [{
                    name: "得分",
                    type: 'bar',
                    barWidth: '30',
                    itemStyle: {
                        normal: {
                            color: '#5c90d2',
                        }
                    },
                    label: {
                        formatter: '{c}%',
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    },
                    markLine: {
                        itemStyle:{
                            normal:{
                            lineStyle:{
                                type:'dashed',
                                color:'red'
                            },
                            label:{
                                show:true,
                                position:"end",//'start' 线的起始点。'middle' 线的中点。'end' 线的结束点。
                                formatter:function(param){
                                    return param.name+param.value
                                },
                                textStyle: {
                                    fontSize: 16,
                                }
                            }
                            }
                        },
                        silent: true,
                        data: [{
                            name: '及格线',
                            yAxis: that.exampaperInfo.passLine
                        }]
                    },
                    data: yData
                }]
            }
            that.$echarts.init(document.getElementById('examineeScoreSortEchart')).setOption(option_echart, true)
        },
        // 获取列表数据
        getTableData(pageIndex, pageSize) {
            let that = this
            that.loading = true
            if (pageIndex) {
                that.currentPage = pageIndex
            }
            if (pageSize) {
                that.pageSize = pageSize
            }
            
            getExamDetailInfo({
                id: this.searchForm.examId,
                status: -1, // 考试状态
                pageIndex: that.currentPage - 1,
                pageSize: that.pageSize,
                queryType: 1
            }).then(res => {
                if(res.status === 200) {
                    that.tableData = res.data
                    that.total = res.total
                }
                that.loading = false
            })
            
        },
        handleSizeChange(pageSize) {
            this.getTableData(1, pageSize)
        },
        handleCurrentChange(currentPage) {
            this.getTableData(currentPage)
        },
        // 导出明细
        exportDetail() {
            let that = this
            let parames = {
                examId: that.searchForm.examId
            }
            let downloadUrl = this.GLOBAL.baseURL + 'exam/exportPersonalExamDetail?examId=' + parames.examId
                
            window.open(downloadUrl)
        },
        // 查看答卷明细
        handleDetail(row) {
            this.currentExamPaperInfo = row
            this.dialogExamPaper = true
        },
        closeExamPaper() {
            this.dialogExamPaper = false
        }
    },
    computed: {
        departmentIdChange() {
            return this.searchForm2.departmentId
        },
        sortTypeChange() {
            return this.searchForm2.sortType
        },
    },
    watch: {
        departmentIdChange(val) {
            if(val) {
                this.searchDepartment()
            }
        },
        sortTypeChange(val) {
            if(val) {
                this.getExamineeScoreSort()
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.one-exam-analysis {
    .department-serach-form {
        margin-top: 20px;
        .el-form-item {
            margin-bottom: 10px;
        }
    }
}
</style>